#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

#define BUFSIZE     4096

int main(int argc, char const* argv[])
{
    int write_fd, read_fd, have_read;
    char buf[BUFSIZE], message[20], clientname[20];

    if (argc != 2)
    {
        fprintf(stderr, "usage: %s <filename>\n", argv[0]);
        exit(0);
    }

    if ((write_fd = open("server", O_WRONLY)) < 0)
    {
        perror("open server error");
        exit(0);
    }

    sprintf(clientname, "client_%d", getpid());
    sprintf(message, "%s:%s", clientname, argv[1]);
    printf("send message: %s\n", message);

    if (write(write_fd, message, strlen(message)) < 0)
    {
        perror("write error");
        exit(0);
    }

    if (mkfifo(clientname, 0600) < 0)
    {
        perror("mkfifo error");
        exit(0);
    }

    if ((read_fd = open(clientname, O_RDONLY)) < 0)
    {
        perror("open error");
        exit(0);
    }

    while ((have_read = read(read_fd, buf, BUFSIZE)) > 0)
    {
        if (write(STDOUT_FILENO, buf, have_read) < have_read)
        {
            perror("write error");
            exit(0);
        }
    }

    if (have_read < 0)
        perror("read error");

    return 0;
}

